package com.changyou.skynet.util;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class SkyNetDaoUtil {
    @Autowired
    private SessionFactory sessionFactory;
    
    /**
     * 获取当前的事物session
     * @return
     */
    public Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }
    
    /**
     * 保存一个对象
     * @param o
     * @return
     */
    public <T> Serializable save(T o) {
        if (o != null) {
            return this.getCurrentSession().save(o);
        }
        return null;
    }
    /**
     * 查看所有数据
     * @param hql
     * @param params
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> find(String hql, Map<String, Object> params) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (null != params && !params.isEmpty()) {
            for (String key : params.keySet()) {
                q.setParameter(key, params.get(key));
            }
        }
        return q.list();
    }
    
    /**
     * 查询对象，通过ID.
     * @param c
     * @param id
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T get(Class<T> c, Serializable id) {
        return (T) this.getCurrentSession().get(c, id);
    }
    /**
     * 删除一个对象
     * @param o
     */
    public <T> void delete(T o) {
        if (o != null) {
            this.getCurrentSession().delete(o);
        }
    }
    
    public Long count(String hql, Map<String, Object> params) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                q.setParameter(key, params.get(key));
            }
        }
        return (Long) q.uniqueResult();
    }
}
